import { Controller, Get, Post, Body, Query, Session, Req } from '@nestjs/common';
import { MessageService } from './message.service';

@Controller('message')
export class MessageController {
  constructor(private readonly messageService: MessageService) { }

  @Get('getMessages')
  async findAll(@Query() query: any, @Session() session: Record<string, any>) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      console.log('查询消息历史，参数:', query, '用户ID:', session.userId);
      // 添加用户ID到查询参数
      const messages = await this.messageService.findAll({
        ...query,
        userId: session.userId
      });

      console.log(`查询到 ${messages.length} 条消息记录`);

      return {
        code: 0,
        data: messages,
        msg: 'success'
      };
    } catch (error) {
      console.error('查询消息历史失败:', error);
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Post('createMessage')
  async create(@Body() createMessageDto: any, @Session() session: Record<string, any>) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      createMessageDto.userId = session.userId;
      const message = await this.messageService.create(createMessageDto);
      return {
        code: 0,
        data: message,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Post('removeMessage')
  async remove(@Body() body: { id: number }, @Session() session: Record<string, any>) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      await this.messageService.remove(body.id);
      return {
        code: 0,
        data: null,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Get('log/getLog')
  async getLog(@Query() query: any, @Session() session: Record<string, any>) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      console.log('查询日志，参数:', query, '用户ID:', session.userId);

      // 使用与getMessages相同的服务方法，但可能有不同的分页或筛选逻辑
      const logs = await this.messageService.findAll({
        ...query,
        userId: session.userId
      });

      console.log(`查询到 ${logs.length} 条日志记录`);

      return {
        code: 0,
        data: logs,
        msg: 'success'
      };
    } catch (error) {
      console.error('查询日志失败:', error);
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }
} 